package com.dream.classinfo;

import android.content.Context;
import android.widget.Toast;

import com.android.volley.NetworkResponse;
import com.android.volley.ParseError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.HttpHeaderParser;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;

/**
 * Created by Administrator on 2017/5/21.
 */

public class HttpData {
    private RequestQueue requestQueue;
    private Context context;
    private String url;

    public HttpData(Context context, String url) {
        requestQueue= MySingleRequestQueue.getMyInstance(context).getRequestQueue();
        this.context=context;
        this.url=url;
    }

    public void getResponse(final getResult getresult){
        StringRequest stringRequest=new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {
                getresult.onSuccess(s);
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                Toast.makeText(context,"请求服务器失败，请检查参数或网络",Toast.LENGTH_SHORT).show();
            }
        }){
            @Override
            protected Response<String> parseNetworkResponse(NetworkResponse response) {
                try {
                    String requestHeader = new String(response.data,"UTF-8");
                    return Response.success(requestHeader, HttpHeaderParser.parseCacheHeaders(response));
                } catch (Exception e) {
                    return Response.error(new ParseError(e));
                }

            }
        };
        requestQueue.add(stringRequest);
    }

    public interface getResult{
        void onSuccess(String result);
    }

}
